<template>
  <div>
    <van-nav-bar
      title="个人信息"
      fixed
      placeholder
      z-index="999"
      left-arrow
      @click-left="$router.back()"
    />
    <van-form @submit="onSubmit">
      <van-cell title="头像" center>
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <template #right-icon>
          <!-- 上传的功能    -->
          <!--  input定位定到img上   透明度0 -->
          <van-uploader :after-read="afterRead">
            <van-button icon="plus" type="primary"> </van-button>
            <van-image round width="60" height="60" :src="userInfo.avatar" />
          </van-uploader>
        </template>
      </van-cell>
      <van-field
        v-model="userInfo.nickname"
        label="昵称"
        name="username"
        input-align="right"
      />
      <van-field name="radio" label="性别" input-align="right">
        <template #input>
          <van-radio-group v-model="userInfo.sex" direction="horizontal">
            <van-radio name="男">男</van-radio>
            <van-radio name="女">女</van-radio>
          </van-radio-group>
        </template>
      </van-field>

      <van-field
        label="生日"
        placeholder="请选择生日"
        name="birthday"
        input-align="right"
        @click="show = true"
        v-model="userInfo.birthday"
      />
      <van-popup v-model="show" position="bottom">
        <van-datetime-picker
          @cancel="show = false"
          @confirm="notarize"
          v-model="currentDate"
            :min-date="minDate"
            :max-date="maxDate"
          type="date"
          title="选择年月日"
        />
        <!-- @change="changeFn()" -->
      </van-popup>
      <van-button type="primary" size="large" native-type="submit"
        >确定</van-button
      >
    </van-form>
  </div>
</template>
<script>
// import { stringify } from "qs";
import { DatetimePicker, Popup } from "vant";
export default {
  name: "userinfo",
  data() {
    return {
      num: 111,
      // username: "",
      // radio: "",
      minDate: new Date(1945, 0, 1),
      maxDate: new Date(),
      show: false,
      timeValue: "", //生日
      currentDate: new Date(),
      // avatar: "",
      userInfo: {},
      changeDate: new Date(),
    };
  },
  components: {
    [DatetimePicker.name]: DatetimePicker,
    [Popup.name]: Popup,
  },
  created() {
    this.geteUserInfo();
  },
  // 挂载后
  mounted() {
    this.timeFormat(new Date());
  },
  methods: {
  //  formatter(type, val) {
  //     if (type === 'year') {
  //       return `${val}年`;
  //     } else if (type === 'month') {
  //       return `${val}月`;
  //     }
  //     return val;
  //   },
  

    async afterRead(file) {
      // 此时可以自行将文件上传至服务器
      console.log(file);
      let { type } = file.file;
      //  拿到类型  比如jpg
      type = type.split("/")[1];
      console.log(type);
      let file_name = `${new Date().getTime()}_${Math.random()
        .toString(36)
        .slice(2)}.${type}`;
      // console.log(file_name);
      // 去自己的服务器拿到上传七牛云需要的 token  为何放在服务端呢?  主要是为了安全，因为里边包含了一些账号信息

      let { token } = await this.$http.post(
        "https://d33a5037-6c63-4e92-8bb1-30018ab701ea.bspapp.com/http" +
          "/upload/token"
      );
      // // new一个form data   并且把文件 token  和文件的名字放进去  file token key是固定的 不能改
      const formdata = new FormData();
      formdata.append("file", file.file);
      formdata.append("token", token);
      formdata.append("key", file_name);
      // https://upload-z1.qiniup.com 是上传到七牛的真正接口  其中z1是华北区域
      let result = await this.$http.post(
        "https://upload-z1.qiniup.com",
        formdata
      );
      let avatar = `http://toutiao.longxiaokj.com/` + result.key;
      this.userInfo.avatar = avatar;
      //  给对象动态的添加属性 并不会触发自动更新
      // this.$forceUpdate()
      console.log(result);
      console.log(`http://toutiao.longxiaokj.com/` + result.key);
      // return result;

      // `http://toutiao.longxiaokj.com/` + result.key  这个地址就是传到服务器的地址
      // 发布文章时 imageSrc  字段需要的就是这个
    },
    onSubmit(values) {
      this.geteditUserInfo();
      //  this.geteUserInfo()
      console.log("submit", values);
      // console.log( this.avatar);
    },
    notarize(value) {
      console.log(value)
      this.show = false;
      this.timeValue = this.timeFormat(this.currentDate);
      console.log(this.timeValue);
      this.userInfo.birthday=this.timeValue
     this.$forceUpdate()
    },
    changeFn() {
      this.changeDate = this.currentDate;
      console.log(this.changeDate);
    },
    timeFormat(time) {
      // 时间格式化 2019-09-08
      let year = time.getFullYear();
      let month = time.getMonth() + 1;
      let day = time.getDate();
       return year + "/" + (month.length>1?month:'0'+month) + "/" +day;
    },

    // 获取用户信息
    geteUserInfo() {
      let token = localStorage.getItem("tt-token");
      this.$http({
        url: "/user/getuserInfo",
        method: "POST",
        //传参
        data: {
          token,
        },
      }).then((res) => {
        console.log(res.userInfo);
        console.log(res);
        this.userInfo = res.userInfo;
      });
    },
    geteditUserInfo() {
      let { birthday, avatar, nickname, sex, _id } = this.userInfo;
      console.log(birthday, avatar, nickname, sex, _id);
      this.$http({
        url: "/user/editUserInfo",
        method: "POST",
        //传参
        data: {
          avatar,
          birthday,
          nickname,
          sex,
          uid: _id,
        },
      })
        .then((res) => {
          console.log(res);
          if (res.code == 0) {
            this.$toast("修改成功");
            // 把修改后的值存到本地
                console.log(res);
            let {userInfo}=this
                console.log(userInfo);
            localStorage.setItem("tt-userInfo", JSON.stringify(userInfo));
            
            this.$store.commit("change", { key: "userInfo", value:userInfo });
            setTimeout((v) => {
              this.$router.back();
            }, 800);
          } else {
            this.$toast("修改失败");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>
<style lang='less' scoped>
::v-deep .van-button--normal {
  position: absolute;
  top: 10px;
  left: 6px;
  display: none;
}
::v-deep .van-button--primary {
  margin: 12px;
  margin-top: 30px;
}
::v-deep .van-button--large {
  width: 90%;
}
</style>